同樣根據以上的Reqres API 來示範
DELETE api 執行後只有status code 來判斷是否刪除成功,故不需要建一個model 來接response
我們在UserURLSession.swift
處理關於URLSession
的事件
func userDeleteRequest(id: Int, completionHandler: @escaping (String) -> Void) {
let url = URL(string: "https://reqres.in/api/users/\(id)")!
var request = URLRequest(url: url)
request.httpMethod = "DELETE"
URLSession.shared.dataTask(with: request) { (data, response, error) in
var statusCode = -1
if let httpResponse = response as? HTTPURLResponse {
statusCode = httpResponse.statusCode
}
if(statusCode == 204){
completionHandler("DELETE Success")
}else{
completionHandler("DELETE Fail")
}
}.resume()
}
之後在View 設計畫面並使用DELETESampleView.swift
:
import SwiftUI
struct DELETESampleView: View {
@State private var response = ""
var body: some View {
NavigationView {
VStack {
Button {
UserURLSession.shared.userDeleteRequest(id: 2) { response in
DispatchQueue.main.async {
self.response = response
}
}
} label: {
Text("DELETE Request")
}
Text("response: \(response)")
}
.navigationBarTitleDisplayMode(.inline)
.navigationTitle(Text("URLSession DELETE Sample"))
}
}
}
struct DELETESampleView_Previews: PreviewProvider {
static var previews: some View {
DELETESampleView()
}
}
這邊所有URLSession 的範例一起放在Github: URLSessionSample 供大家參考